﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace IronLua.Metadata
{
    
    [StructLayout(LayoutKind.Explicit)]
    public struct Constant
    {

        public Constant(int index)
        {
            this.Index = index;
            this.Value = Value.Nil;
        }

        public Constant(int index, bool boolean)
        {
            this.Index = index;
            this.Value = Value.FromBoolean(boolean);
        }

        public Constant(int index, string str)
        {
            this.Index = index;
            this.Value = Value.FromString(str);
        }

        public Constant(int index, double number)
        {
            this.Index = index;
            this.Value = Value.FromDouble(number);
        }

        [FieldOffset(0)]
        public readonly int Index;

        [FieldOffset(8)]
        internal readonly Value Value;

        public string String { get { return this.Value.String; } }
        public double Number { get { return this.Value.Number; } }
        public bool Boolean { get { return this.Value.Boolean; } }

        public override string ToString()
        {
            switch (this.Value.Type)
            {
                case ValueType.Nil:
                    return "k[{0}] = nil".FormatWith(this.Index);
                case ValueType.Boolean:
                    return "k[{0}] = {1}".FormatWith(this.Index, this.Boolean.ToString());
                case ValueType.Number:
                    return "k[{0}] = {1}".FormatWith(this.Index, this.Number.ToString());
                case ValueType.String:
                    return "k[{0}] = \"{1}\"".FormatWith(this.Index, this.String);
                default:
                    return "k[{0}] = ???".FormatWith(this.Index);
            }
        }

    }
}
